﻿#include "board.h"
#include <QPainter>

#define CELL_WIDTH 136
#define CELL_HEIGHT 160
#define CELL_MARGIN 16
#define BOARD_WIDTH (CELL_WIDTH * 4 + CELL_MARGIN * 5)
#define BOARD_HEIGHT (CELL_HEIGHT * 4 + CELL_MARGIN * 5)

Board::Board(QGraphicsScene *scene):
    m_scene(scene)
{
    m_scene->addItem(this);
    drawFace();

    this->setFlag(QGraphicsItem::ItemIsFocusable);
    //this->setFlag(QGraphicsItem::ItemIsMovable);

}

Board::~Board()
{

}

QPoint Board::firstPoint()
{
    int first_x = pos().x() - (CELL_WIDTH + CELL_MARGIN) / 2 * 3;
    int first_y = pos().y() - CELL_HEIGHT / 2 * 3 - CELL_MARGIN * 2 - 4;

    return QPoint(first_x, first_y);
}

QRectF Board::boundingRect() const
{
    return QRectF(-BOARD_WIDTH / 2, -BOARD_HEIGHT / 2, BOARD_WIDTH, BOARD_HEIGHT);
}

void Board::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
    // 镇压宏
    Q_UNUSED(option);
    Q_UNUSED(widget)

    painter->setRenderHint(QPainter::Antialiasing, true);
    painter->setRenderHint(QPainter::SmoothPixmapTransform, true);

    painter->drawImage(boundingRect(), m_face->toImage());
}

void Board::drawFace()
{
    m_face = new QPixmap(BOARD_WIDTH, BOARD_HEIGHT);
    m_face->fill(Qt::transparent); // 初始化为透明，以便后续绘制背景

    QPainter painter(m_face);
    painter.setRenderHint(QPainter::Antialiasing); // 抗锯齿，使绘制更平滑
    QPen pen;

    // 绘制线
    pen.setCapStyle(Qt::RoundCap);
    pen.setJoinStyle(Qt::RoundJoin);
    pen.setWidth(CELL_MARGIN);
    pen.setColor(QColor(211, 147, 89));
    painter.setPen(pen);

    // 横线
    for(int i = 0; i < 5; i++){
        QPoint source(12, (CELL_HEIGHT + CELL_MARGIN) * i + CELL_MARGIN / 2);
        QPoint destin(BOARD_WIDTH - 12, (CELL_HEIGHT + CELL_MARGIN) * i + CELL_MARGIN / 2);
        painter.drawLine(source, destin);
    }

    // 竖线
    for(int i = 0; i < 5; i++){
        QPoint source((CELL_WIDTH + CELL_MARGIN) * i + CELL_MARGIN / 2, 12);
        QPoint destin((CELL_WIDTH + CELL_MARGIN) * i + CELL_MARGIN / 2, BOARD_HEIGHT - 12);
        painter.drawLine(source, destin);
    }

    // 绘制边框
    QString strFace = ":/Monster_Kill/Res/Img/Frame.png";
    painter.drawPixmap(-27, -6, QPixmap(strFace)
                       .scaled(BOARD_WIDTH + 54, BOARD_HEIGHT + 18,
                               Qt::IgnoreAspectRatio, Qt::SmoothTransformation));

    painter.end();
}

bool Board::collidesWithItem(const QGraphicsItem *other, Qt::ItemSelectionMode mode) const
{
    Q_UNUSED(other);
    Q_UNUSED(mode);

    return false;
}

bool Board::collidesWithPath(const QPainterPath &path, Qt::ItemSelectionMode mode) const
{
    Q_UNUSED(path);
    Q_UNUSED(mode);

    return false;
}


